#include<unistd.h>
#include<signal.h>
#include<workflow/WFTaskFactory.h>
#include<workflow/WFFacilities.h>
#include<workflow/Workflow.h>
#include<string>
#include<iostream>

using std::cout;
using std::cerr;
using std::string;
struct context
{
    string resp;
};
static WFFacilities::WaitGroup waitGroup(1);
void sighandler(int signum){
    waitGroup.done();
}


void rediscallback(WFRedisTask* task)
{
    protocol::RedisResponse* resp= task->get_resp();
    int state= task->get_state();
    int error = task->get_error();
    protocol::RedisValue val;
    switch(state)
    {
        	case WFT_STATE_SYS_ERROR:
		cerr <<"system error: " << strerror(error) << "\n";
		break;
	case WFT_STATE_DNS_ERROR:
		cerr <<"DNS error: "  << gai_strerror(error) << "\n";
		break;
	case WFT_STATE_SSL_ERROR:
		cerr <<"SSL error\n";
		break;
	case WFT_STATE_TASK_ERROR:
		cerr <<"Task error\n";
		break;
        case WFT_STATE_SUCCESS: 
            resp->get_result(val);
            if(val.is_error())
            {
                cerr<<"maybe need a passwd\n";
            cout<<"task run error: "<<static_cast<struct context*>(series_of(task)->get_context())<<"\n";
                state=WFT_STATE_TASK_ERROR;
            }
            break;
    }
            if(state!=WFT_STATE_SUCCESS)
            {
                cerr<<"failed\n";
                return;
            }
             if(val.is_string())
            {
    WFRedisTask * redistask = WFTaskFactory::create_redis_task("redis://127.0.0.1:6379",10,rediscallback);
    redistask->get_req()->set_request("GET",{val.string_value()});
    SeriesWork* serieswork=series_of(task);
    struct context* serisecontext = static_cast <struct context*>( serieswork->get_context());
    serisecontext->resp=val.string_value();
    serieswork->push_back(redistask);
        }
        else
        {

            cout<<"task run error: "<<static_cast<struct context*>(series_of(task)->get_context())->resp<<"\n";
        }
}

void seriescallback(const SeriesWork* serieswork)
{
    delete static_cast<struct context*>(serieswork->get_context());
    cout<<" series finished\n";
}
int main(void)
{
    signal(SIGINT,sighandler);
    //新建任务
    WFRedisTask * redistask = WFTaskFactory::create_redis_task("redis://127.0.0.1:6379",10,rediscallback);
    redistask->get_req()->set_request("GET",{"x1"});
    //新建序列
    SeriesWork* serieswork = Workflow::create_series_work(redistask,nullptr);
    struct context* text =new struct context;
    text->resp="x1";
    serieswork->set_context(text);
    serieswork->set_callback([text](const SeriesWork* series){
        delete text;
    });
    serieswork->start();
    waitGroup.wait();
    cout<<"finished\n";
}
